package com.yc.bigdata.hbase.support;

import com.google.common.collect.Lists;
import com.yc.bigdata.hbase.core.HBaseTemplate;

import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * <p></p>
 *
 * @author: YuanChilde
 * @date: 2020-01-16 17:03
 * @version: 1.0
 * Modification History:
 * Date    Author      Version     Description
 * -----------------------------------------------------------------
 * 2020-01-16 17:03    YuanChilde     1.0        新增
 */
@Repository
public class UserRepository {
    @Autowired
    private HBaseTemplate hBaseTemplate;

    private String tableName = "users";

    public static byte[] CF_INFO = Bytes.toBytes("cfInfo");

    private byte[] qUser = Bytes.toBytes("user");
    private byte[] qEmail = Bytes.toBytes("email");
    private byte[] qPassword = Bytes.toBytes("password");

    public List<User> findAll() {
        return hBaseTemplate.find(tableName, "cfInfo", (result, rowNum) ->
                new User(Bytes.toString(result.getValue(CF_INFO, qUser)),
                Bytes.toString(result.getValue(CF_INFO, qEmail)),
                Bytes.toString(result.getValue(CF_INFO, qPassword))));

    }

    public User save(final String userName, final String email,
                     final String password) {
        return hBaseTemplate.execute(tableName, table -> {
            User user = new User(userName, email, password);
            Put p = new Put(Bytes.toBytes(user.getName()));
            p.addColumn(CF_INFO, qUser, Bytes.toBytes(user.getName()));
            p.addColumn(CF_INFO, qEmail, Bytes.toBytes(user.getEmail()));
            p.addColumn(CF_INFO, qPassword, Bytes.toBytes(user.getPassword()));
            table.put(p);
            return user;
        });
    }

    public void saveOrUpdate() {
        List<Mutation> saveOrUpdates = Lists.newArrayList();
        Put put = new Put(Bytes.toBytes("135xxxxxx"));
        put.addColumn(Bytes.toBytes("people"), Bytes.toBytes("name"), Bytes.toBytes("test"));
        saveOrUpdates.add(put);
        this.hBaseTemplate.saveOrUpdates("people_table", saveOrUpdates);
    }

}
